package gamesys.games.particlesystem.particleloader
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;

	/**
	 * @author robertthurston
	 */
	public class ParticleLoader extends EventDispatcher
	{
		private var _assetQueue : int;
		
		public function ParticleLoader()
		{
			_assetQueue = 0;
		}

		public function loadAssets(assetsToLoad : Array) : void
		{
			_assetQueue += assetsToLoad.length;
			
			for each(var url : String in assetsToLoad)
			{
				loadViaLoader(url);
			}
		}
		
		private function loadViaLoader(url : String) : void
		{
			var request : URLRequest = new URLRequest(url);
			var loader : Loader = new Loader();

			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onGraphicalLoadComplete);
			loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);

			loader.load(request, new LoaderContext(false, ApplicationDomain.currentDomain));
		}

		private function onIOError(event : IOErrorEvent) : void
		{
			trace("onIOError");
		}

		private function onSecurityError(event : SecurityErrorEvent) : void
		{
			trace("onSecurityError");
		}

		private function onGraphicalLoadComplete(event : Event) : void
		{
			_assetQueue--;
			
			if(_assetQueue == 0)
			{
				dispatchEvent(new ParticleLoaderEvent(ParticleLoaderEvent.COMPLETE));
			}
		}
	}
}
